package com.example.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import com.example.consumer.model.User;

@RestController
@RequestMapping("/api/consumer/rest-template")
public class RestTemplateTestController {

    @Autowired
    private RestTemplate restTemplate;

    private final String SERVICE_URL = "http://provider-service/api/users";

    @GetMapping("/users")
    public ResponseEntity<?> getAllUsers() {
        try {
            return restTemplate.getForEntity(SERVICE_URL, User[].class);
        } catch (HttpClientErrorException e) {
            return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
        }
    }

    @PostMapping("/users")
    public ResponseEntity<?> createUser(@RequestBody User user) {
        try {
            return restTemplate.postForEntity(SERVICE_URL, user, String.class);
        } catch (HttpClientErrorException e) {
            return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
        }
    }

    @GetMapping("/users/{id}")
    public ResponseEntity<?> getUser(@PathVariable("id") Long id) {
        try {
            return restTemplate.getForEntity(SERVICE_URL + "/" + id, User.class);
        } catch (HttpClientErrorException e) {
            return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
        }
    }

    @PutMapping("/users/{id}")
    public ResponseEntity<?> updateUser(@PathVariable("id") Long id, @RequestBody User user) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json");
            HttpEntity<User> requestEntity = new HttpEntity<>(user, headers);
            return restTemplate.exchange(SERVICE_URL + "/" + id, HttpMethod.PUT, requestEntity, String.class);
        } catch (HttpClientErrorException e) {
            return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
        }
    }

    @DeleteMapping("/users/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable("id") Long id) {
        try {
            restTemplate.delete(SERVICE_URL + "/" + id);
            return ResponseEntity.ok("User with ID " + id + " deleted successfully via RestTemplate.");
        } catch (HttpClientErrorException e) {
            return ResponseEntity
                    .status(e.getStatusCode())
                    .body("Error from provider: " + e.getResponseBodyAsString());
        }
    }
} 